package com.test.down;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.airbnb.lottie.LottieAnimationView;
import com.test.down.utils.Utils;

import java.util.Locale;

import tv.danmaku.ijk.media.exo.demo.widget.media.IjkVideoView;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * @author he xiaohui
 */
@SuppressLint({"NewApi", "DefaultLocale"})
public class VideoViewController extends LinearLayout {
    /**
     * 隐藏进度栏
     **/
    private static final int HIDE_PROGRESS = 1;

    /**
     * 隐藏视频截图
     */
    private static final int HIDE_VIDEO_SCREENSHOT = 1001;

    private static final int DELAY_HIDE_TIME = 5000;

    private static final int PRISED_ANIM_END = 5001;

    public static boolean fullScreen;

    public int initVideoHeight;

    public int videoWidth;
    public int videoHeight;

    public OnCompleteListener completeListener;

    public OnPlayListener playListener;

    public OnScreenChangeListener screenChangeListener;

    public OnVideoDownLoadListener onVideoDownLoadListener;

    /**
     * 播放进度改变
     **/
    public OnPlayProgressListener progressListener;

    private Context context;

    private Activity activity;

    private IjkVideoView surface_view;

    private SeekBar mediacontroller_seekbar;

    private ImageView play_btn, play_btn_bottom_left, volume_img;

    private ImageView loading, fullscreen_tv, fullscreen_tv_bottom_right;

    private View danmubtn_down;

    private ImageView danmubtn_down_img;

    private ImageButton danmu_btn;

    private TextView nowtime_tv, totaltime_tv;

    private View fullscreen_shot_layout, progress_layout;

    private ImageView image_fullscreen_shot;

    private View fullscreen_prised;//点赞

    private View fullscreen_shot_btn;//截屏

//    private LottieAnimationView img_fullscreen_prised;

    private View progressbar;

    private boolean mDragging;

    private int phoneheight, phonewidth;

    private View parentView;

    public int Commentable;//0:没有互动聊天

    public int IsShowHeart;//0:不显示

    public int heartCount;

    private View currentItem;

    public long mDuration;

    private Bitmap videoShotBitmap;

    private boolean openDanmu = true;

    private boolean isFullScreenToPortrait;//竖屏横屏

    private EditText fullscreen_edittext;

    private TextView fullscreen_prised_num_tv;

    public int IsVerticalScreen;

    private long seekProgress = 0;

    private LinearLayout mFullScreen;

    private RelativeLayout relateTopConteoller;
    private ImageView ivDownLoad;

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (null != activity && !activity.isFinishing()) {
                switch (msg.what) {
                    case 0:
                        if (0 == mDuration) {
                            mDuration = surface_view.getDuration();
                        }
                        break;
                    case HIDE_PROGRESS:
                        if (null != controller_bottom) {
                            setVideoFloatViewVisibility(false);
                            Utils.hideSoftKeyboard((Activity) context);
                        }
                        if (null != onVideoClickListener) {
                            onVideoClickListener.onVideClick(false, true);
                        }
                        break;
                    case HIDE_VIDEO_SCREENSHOT:
                        fullscreen_shot_layout.setVisibility(View.GONE);
                        break;
                    case PRISED_ANIM_END:
//                        img_fullscreen_prised.cancelAnimation();
//                        img_fullscreen_prised.setProgress(0);
                        break;
                }
            }
            return false;
        }
    });

    public void setHeartCount(int heartCount) {
        this.heartCount = heartCount;
        if (null != fullscreen_prised_num_tv) {
            fullscreen_prised_num_tv.setText(String.valueOf(heartCount));
        }
    }

    Runnable runnable = new Runnable() {

        @Override
        public void run() {
            setProgress();
            handler.postDelayed(runnable, 1000);
        }
    };

    int position = -1;

    private View controller_bottom, progressview, live_reply_layout;

    private boolean mInstantSeeking = true;

    private boolean isCompletion;

    private String playUrl = "";

    public interface OnVideoClickListener {
        public void onVideClick(boolean isShow, boolean isAuto);
    }

    public OnVideoClickListener onVideoClickListener;

    public void setmFullScreen(LinearLayout mFullScreen) {
        this.mFullScreen = mFullScreen;
    }

    private OnClickListener clickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            boolean isShow = false;
            if (for_screen) {
                return;
            }
            if (controller_bottom.isShown()) {
                isShow = false;
                handler.removeMessages(HIDE_PROGRESS);
                setVideoFloatViewVisibility(false);
                Utils.hideSoftKeyboard((Activity) context);
            } else {
                isShow = true;
                setVideoFloatViewVisibility(true);
                setfullscreenEdittextFocusable(false);
                showHideProgressInfo();
            }
            if (null != onVideoClickListener) {
                onVideoClickListener.onVideClick(isShow, false);
            }
        }
    };

    void setVideoFloatViewVisibility(boolean isShow) {
        controller_bottom.setVisibility(isShow ? View.VISIBLE : View.GONE);
        relateTopConteoller.setVisibility(isShow ? View.VISIBLE : View.GONE);
        fullscreen_prised.setVisibility(isShow && isFullScreen && 0 != IsShowHeart ? View.VISIBLE : View.INVISIBLE);
//        fullscreen_shot_btn.setVisibility(isShow && isFullScreen ? View.VISIBLE : View.INVISIBLE);
        fullscreen_shot_btn.setVisibility(GONE);
    }

    private boolean isLive;

    /**
     * @param context
     */
    public VideoViewController(Context context) {
        super(context);
        init(context);
    }

    /**
     * @param context
     * @param attrs
     */
    public VideoViewController(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private static String generateTime(long position) {
        int totalSeconds = (int) (position / 1000);

        int seconds = totalSeconds % 60;
        int minutes = (totalSeconds / 60) % 60;
        int hours = totalSeconds / 3600;

        if (hours > 0) {
            return String.format(Locale.US, "%02d:%02d:%02d", hours, minutes, seconds).toString();
        } else {
            return String.format(Locale.US, "%02d:%02d", minutes, seconds).toString();
        }
    }

    public void setFullScreenToPortrait(boolean fullScreenToPortrait) {
        isFullScreenToPortrait = fullScreenToPortrait;
    }

    public interface OnSeekChangeListener {
        public void onSeekChange(int position);
    }

    public OnSeekChangeListener onSeekChangeListener;

    public void init(final Context context) {
        this.context = context;
        activity = (Activity) context;
        isCompletion = true;
        fullScreen = false;

        View view = LayoutInflater.from(context).inflate(R.layout.mycontraller_layout, null);
        addView(view, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        controller_bottom = view.findViewById(R.id.controller_bottom);
        progress_layout = view.findViewById(R.id.progress_layout);

        progressbar = view.findViewById(R.id.progressbar);
        progressview = view.findViewById(R.id.progressview);
        mediacontroller_seekbar = (SeekBar) view.findViewById(R.id.mediacontroller_seekbar);
        nowtime_tv = (TextView) view.findViewById(R.id.nowtime_tv);
        totaltime_tv = (TextView) view.findViewById(R.id.totaltime_tv);
        danmu_btn = (ImageButton) view.findViewById(R.id.danmubtn);
        loading = view.findViewById(R.id.loading);

        live_reply_layout = view.findViewById(R.id.live_reply_layout);
        danmubtn_down = view.findViewById(R.id.danmubtn_down);
        danmubtn_down_img = view.findViewById(R.id.danmubtn_down_img);
        fullscreen_edittext = view.findViewById(R.id.fullscreen_edittext);
        fullscreen_shot_btn = view.findViewById(R.id.fullscreen_shot_btn);
//        img_fullscreen_prised = view.findViewById(R.id.img_fullscreen_prised);
//        ViewGroup.LayoutParams lp = img_fullscreen_prised.getLayoutParams();
//        lp.height = lp.width = Utils.dip2px(context, 50);
//        img_fullscreen_prised.setLayoutParams(lp);
        // MediaController mediaController = new MediaController(context);
        // surface_view.setMediaController(mediaController);

        play_btn = (ImageView) view.findViewById(R.id.play_btn);
        play_btn_bottom_left = view.findViewById(R.id.play_btn_bottom_left);
        volume_img = (ImageView) view.findViewById(R.id.volume_img);
        volume_img.setVisibility(View.GONE);
        fullscreen_tv = view.findViewById(R.id.fullscreen_tv);
        fullscreen_tv_bottom_right = view.findViewById(R.id.fullscreen_tv_bottom_right);
        if (context instanceof FullVideoActivity) {
            fullscreen_tv.setVisibility(View.GONE);
            fullscreen_tv_bottom_right.setVisibility(View.GONE);
        }

        fullscreen_shot_layout = view.findViewById(R.id.fullscreen_shot_layout);
        image_fullscreen_shot = view.findViewById(R.id.image_fullscreen_shot);
        fullscreen_prised = view.findViewById(R.id.fullscreen_prised);
        fullscreen_prised_num_tv = view.findViewById(R.id.fullscreen_prised_num_tv);
        RelativeLayout.LayoutParams lp2 = (RelativeLayout.LayoutParams) fullscreen_prised_num_tv.getLayoutParams();
        lp2.topMargin = Utils.dip2px(context, 17);
        lp2.leftMargin = -Utils.dip2px(context, 16);
        fullscreen_prised_num_tv.setLayoutParams(lp2);

        relateTopConteoller=view.findViewById(R.id.relate_top_controller);
        ivDownLoad=view.findViewById(R.id.iv_url_down_load);

        initListener(view);
    }

    public void hiddenDownLoad(boolean hidden){
        if(hidden){
            ivDownLoad.setVisibility(View.GONE);
        }else {
            ivDownLoad.setVisibility(View.VISIBLE);
        }
    }

    private void initListener(View view) {
        view.findViewById(R.id.fullscreen_prised_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                showHideProgressInfo();
//                img_fullscreen_prised.playAnimation();
                if (null != onHeartListener) {
                    onHeartListener.onHeart();
                }
            }
        });
        mediacontroller_seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            boolean fromUser;

            int progress;

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mDragging = false;
                seekProgress = progress;
                if (!fromUser) {
                    return;
                }
                long newposition = (mDuration * progress) / 1000;
                String time = generateTime(newposition);
                if (mInstantSeeking) {
                    surface_view.seekTo((int) newposition);
                }
                if (nowtime_tv != null) {
                    nowtime_tv.setText(time);
                }
                if (null != onSeekChangeListener) {
                    onSeekChangeListener.onSeekChange(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mDragging = true;
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                this.progress = progress;
                this.fromUser = fromUser;
                nowtime_tv.setText(generateTime((mDuration * progress) / 1000));
            }
        });


        play_btn.setOnClickListener(playBtnListener);
        play_btn_bottom_left.setOnClickListener(playBtnListener);

        fullscreen_tv.setOnClickListener(fullScreenBtnListener);
        fullscreen_tv_bottom_right.setOnClickListener(fullScreenBtnListener);
        danmu_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openOrCloseDanmu();
            }
        });
        danmubtn_down.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                openOrCloseDanmu();
            }
        });
        setfullscreenEdittextFocusable(false);
        fullscreen_edittext.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setfullscreenEdittextFocusable(true);
                Utils.showSoftKeyBoard((Activity) context, fullscreen_edittext);
                handler.removeMessages(HIDE_PROGRESS);
            }
        });
        fullscreen_edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //TODO 发送弹幕
                    if (null != fullScreenReplyListener) {
                        fullScreenReplyListener.onFullScreenReply(fullscreen_edittext);
                    }
                    showHideProgressInfo();
                }
                return false;
            }
        });
        fullscreen_shot_btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Bitmap bitmap = surface_view.getShortcut();
                fullscreen_shot_layout.setVisibility(View.VISIBLE);
                boolean isFullScreen = context.getResources().getConfiguration().orientation == Configuration
                        .ORIENTATION_LANDSCAPE;
                ViewGroup.LayoutParams lp = image_fullscreen_shot.getLayoutParams();
                lp.width = Utils.dip2px(context, isFullScreen ? 200 : 100);
                lp.height = Utils.dip2px(context, isFullScreen ? 100 : 100);
                image_fullscreen_shot.setImageBitmap(bitmap);
                if (null != videoShotBitmap) {
                    videoShotBitmap.recycle();
                    videoShotBitmap = null;
                }
                videoShotBitmap = bitmap;
                showHideProgressInfo();
                handler.removeMessages(HIDE_VIDEO_SCREENSHOT);
                handler.sendEmptyMessageDelayed(HIDE_VIDEO_SCREENSHOT, DELAY_HIDE_TIME);
            }
        });
        fullscreen_shot_layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                image_fullscreen_shot.setImageBitmap(null);
                fullscreen_shot_layout.setVisibility(View.GONE);
            }
        });

        ivDownLoad.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onVideoDownLoadListener!=null){
                    onVideoDownLoadListener.onVideoDownLoad();
                }
            }
        });
    }

    private OnClickListener playBtnListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (surface_view.isPlaying()) {
                surface_view.pause();
                changePlayImage(true);
            } else if (isCompletion) {
                if (null != rePlayListener) {
                    rePlayListener.rePlay();
                }
                play(playUrl);
            } else {
                surface_view.start();
                changePlayImage(false);
            }
        }
    };

    private OnClickListener fullScreenBtnListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            changeScreen();
            showHideProgressInfo();
        }
    };

    private void setfullscreenEdittextFocusable(boolean focusable) {
        fullscreen_edittext.setFocusable(focusable);
        fullscreen_edittext.setFocusableInTouchMode(focusable);
    }

    public void openOrCloseDanmu() {
        openDanmu = !openDanmu;
        danmu_btn.setImageResource(openDanmu ? R.drawable.danmuon_white : R.drawable.danmuoff_white);
        danmubtn_down_img.setBackgroundResource(openDanmu ? R.drawable.icon_full_portrait_danmu_open : R.drawable.icon_full_portrait_danmu_close);
        if (null != onDanmuOpenListener) {
            onDanmuOpenListener.onDanmuOpen(openDanmu);
        }
    }

    public boolean for_screen = false;

    public void setProgressHide(boolean for_screen) {
        this.for_screen = for_screen;
        if (for_screen) {
            setVideoFloatViewVisibility(false);
            Utils.hideSoftKeyboard((Activity) context);
        } else {
            //    progress_layout.setVisibility(VISIBLE);
        }

    }

    public void showHeart(String value) {
//        if (null != img_fullscreen_prised) {
//            img_fullscreen_prised.playAnimation();
//        }
        if (Utils.validNum(value)) {
            setHeartCount(Integer.parseInt(value));
        }
    }

    public interface OnRePlayListener {
        public void rePlay();
    }

    public OnRePlayListener rePlayListener;

    /**
     * 开启/关闭弹幕
     *
     * @param isOpenDanmu
     */
    public void openDanmu(boolean isOpenDanmu) {
        openDanmu = isOpenDanmu;
        danmu_btn.setImageResource(openDanmu ? R.drawable.danmuon_white : R.drawable.danmuoff_white);
        danmubtn_down_img.setBackgroundResource(openDanmu ? R.drawable.icon_full_portrait_danmu_open : R.drawable.icon_full_portrait_danmu_close);
    }

    public OnDanmuOpenListener onDanmuOpenListener;

    public interface OnDanmuOpenListener {
        public void onDanmuOpen(boolean isOpenDanmu);
    }

    /**
     * 显示弹幕按钮
     *
     * @param isShow
     */
    public void showDanmuBtn(boolean isShow) {
        danmu_btn.setVisibility(isShow && !isFullScreenToPortrait && 0 != Commentable ? View.VISIBLE : View.GONE);
//        danmubtn_down.setVisibility(isShow && isFullScreenToPortrait && isFullScreen ? View.VISIBLE : View.GONE);
    }

    /**
     * 横竖屏切换
     */
    public void changeScreen() {
        if (isFullScreenToPortrait) {
            isFullScreen = !isFullScreen;
            if (isFullScreen) {
                controller_bottom.setPadding(0, 0, Utils.dip2px(context, 20), 0);
                live_reply_layout.setVisibility(0 != Commentable ? View.VISIBLE : View.GONE);
                fullscreen_prised.setVisibility(0 != IsShowHeart ? View.VISIBLE : View.INVISIBLE);
//                fullscreen_shot_btn.setVisibility(0 != Commentable ? View.VISIBLE : View.INVISIBLE);
                fullscreen_shot_btn.setVisibility(GONE);
//                ((Activity) context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager
//                        .LayoutParams.FLAG_FULLSCREEN);
            } else {
                controller_bottom.setPadding(0, 0, 0, 0);
                live_reply_layout.setVisibility(View.GONE);
                fullscreen_prised.setVisibility(View.INVISIBLE);
//                fullscreen_shot_btn.setVisibility(View.INVISIBLE);
                fullscreen_shot_btn.setVisibility(GONE);
//                ((Activity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            }
            changeSize(parentView, isFullScreen);
            changeSize(surface_view, isFullScreen);
        } else {
            isFullScreen = context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
            if (isFullScreen) {
//                setHideVirtualKey(activity.getWindow());
                if (0 == Commentable || !isLive) //没有互动聊天
                {
                    danmu_btn.setVisibility(View.GONE);
                    live_reply_layout.setVisibility(View.GONE);
                    progress_layout.setVisibility(View.VISIBLE);
                } else {
                    live_reply_layout.setVisibility(View.VISIBLE);
                    progress_layout.setVisibility(View.GONE);
                }
                fullscreen_prised.setVisibility(0 != IsShowHeart ? View.VISIBLE : View.INVISIBLE);
//                fullscreen_shot_btn.setVisibility(0 != Commentable ? View.VISIBLE : View.INVISIBLE);
                fullscreen_shot_btn.setVisibility(GONE);
                play_btn_bottom_left.setVisibility(View.VISIBLE);
                fullscreen_tv_bottom_right.setVisibility(View.VISIBLE);
                changeScreenToLandscape();
            } else {
                live_reply_layout.setVisibility(View.GONE);
                fullscreen_prised.setVisibility(View.INVISIBLE);
//                fullscreen_shot_btn.setVisibility(View.INVISIBLE);
                fullscreen_shot_btn.setVisibility(GONE);
                progress_layout.setVisibility(View.VISIBLE);
                play_btn_bottom_left.setVisibility(View.GONE);
                fullscreen_tv_bottom_right.setVisibility(View.GONE);
                changeScreenToPortrait();
            }
        }
        if (null != screenChangeListener) {
            screenChangeListener.onScreenChange(isFullScreen);
        }
        changeFullScreenViewImg(isFullScreen);
    }

    public void changeFullScreenViewImg(boolean isFullScreen) {
        if (isFullScreenToPortrait) {
            fullscreen_tv.setImageResource(isFullScreen ? R.drawable.zoomout_portrait : R.drawable.zoomin_portrait);
            fullscreen_tv_bottom_right.setImageResource(isFullScreen ? R.drawable.zoomout_portrait : R.drawable.zoomin_portrait);
        } else {
            fullscreen_tv.setImageResource(isFullScreen ? R.drawable.zoomout : R.drawable.zoomin);
            fullscreen_tv_bottom_right.setImageResource(isFullScreen ? R.drawable.zoomout : R.drawable.zoomin);
        }
    }

    public boolean isFullScreen;

    public void isLivePlay(boolean isLive) {
        this.isLive = isLive;
        if (isLive) {
            handler.removeCallbacks(runnable);
//            if (null != play_btn)
//            {
//                play_btn.setVisibility(View.GONE);
//            }
        }
        progressview.setVisibility(isLive ? View.INVISIBLE : View.VISIBLE);
    }

    /**
     * 切换到横屏
     */
    public void changeScreenToLandscape() {
        Log.d("========", "changeScreenToLandscape");
        fullScreen = true;
        ((Activity) context).getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager
                .LayoutParams.FLAG_FULLSCREEN);
        if (!isFullScreenToPortrait) {
            ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {

        }
//        parentView.setX(0);
//        parentView.setY(0);
        changeSize(parentView, true);
        changeSize(surface_view, true);

    }

    /**
     * 切换到竖屏
     */
    public void changeScreenToPortrait() {
        Log.d("========", "changeScreenToPortrait");
        fullScreen = false;
        changeFullScreenViewImg(false);
        changeSize(parentView, false);
        changeSize(surface_view, false);
        ((Activity) context).getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (!isFullScreenToPortrait) {
            ((Activity) context).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {

        }
    }

    public void changePlayImage(boolean toPlay) {
        play_btn.setBackgroundResource(toPlay ? R.drawable.btn_play : R.drawable.btn_pause);
        play_btn_bottom_left.setBackgroundResource(toPlay ? R.drawable.btn_play : R.drawable.btn_pause);
        if (null != onPlayListener) {
            onPlayListener.play(toPlay);
        }
    }

    public OnPlayOpenListener onPlayListener;

    public interface OnPlayOpenListener {
        public void play(boolean isPlay);
    }

    public void changeSize(boolean isFullScreen) {
        changeSize(parentView, isFullScreen);
        changeSize(surface_view, isFullScreen);
    }

    public void changeSize(View view, boolean isFullScreen) {
        // getScreenSize();
        ViewGroup.LayoutParams lp = view.getLayoutParams();
        if (isFullScreen) {
            if (view == parentView) {
                lp.height = isFullScreenToPortrait ? (MyApplication.height + Utils.getNavigationBarHeight(activity)) : MyApplication.width;
                lp.width = isFullScreenToPortrait ? MyApplication.width : (MyApplication.height + Utils.getNavigationBarHeight(activity));
            } else {
                if (isFullScreenToPortrait) {
                    lp.width = MyApplication.width;
                    if (videoHeight > 0 && videoWidth > 0) {
                        lp.height = lp.width * videoHeight / videoWidth;
                        if (lp.height > MyApplication.height + Utils.getNavigationBarHeight(activity)) {
                            lp.height = MyApplication.height + Utils.getNavigationBarHeight(activity);
                            lp.width = lp.width * videoHeight / videoWidth;
                        }
                    }
                } else {
                    lp.width = MyApplication.height + Utils.getNavigationBarHeight(activity);
                    lp.height = MyApplication.width;
                    if (videoWidth > 0 && videoHeight > 0) {
                        lp.height=lp.width * videoHeight / videoWidth;

                    }
                }
            }
        } else {
            lp.height = initVideoHeight > 0 ? initVideoHeight : MyApplication.width * 470 / 840;
            if (view == surface_view) {
                lp.width = MyApplication.width;
            } else {
                lp.width = MyApplication.width;
            }
        }
        Log.d("################", lp.height + "   " + lp.width);
        view.setLayoutParams(lp);
        if (view == surface_view) {
            surface_view.setVideoLayout(IjkVideoView.VIDEO_LAYOUT_SCALE);
        }
    }

    @SuppressWarnings("deprecation")
    protected void getScreenSize() {
        WindowManager manage = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = manage.getDefaultDisplay();
        phoneheight = display.getHeight();
        phonewidth = display.getWidth();
    }

    public void setSurface_view(final View parentView, final IjkVideoView surface_view) {
        this.parentView = parentView;
        parentView.setBackgroundResource(R.drawable.ic_black_bg);
        this.surface_view = surface_view;
        surface_view.setRender(2);
        parentView.setOnClickListener(clickListener);
        surface_view.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(IMediaPlayer iMediaPlayer) {
                seekProgress = 0;
                isCompletion = true;
                handler.removeCallbacks(runnable);
                if (nowtime_tv != null && mDuration > 0) {
                    nowtime_tv.setText(generateTime(mDuration));
                }
                progressbar.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
                changePlayImage(true);
                surface_view.seekTo(0);
                surface_view.stopPlayback();
                if (null != completeListener) {
                    completeListener.onCompletion();
                }
                boolean isFull = context.getResources().getConfiguration().orientation == Configuration
                        .ORIENTATION_LANDSCAPE;
                if (isFull) {
                    isFullScreen = !isFull;
                    changeScreenToPortrait();
                    if (null != screenChangeListener) {
                        screenChangeListener.onScreenChange(!isFull);
                    }
                }
            }
        });
        surface_view.setOnErrorListener(new IMediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(IMediaPlayer iMediaPlayer, int i, int i1) {
                return false;
            }
        });
        surface_view.setOnPreparedListener(new IMediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(IMediaPlayer iMediaPlayer) {
                if (null != preparedListener) {
                    preparedListener.onPrepared(iMediaPlayer);
                }
                progressbar.setVisibility(View.GONE);
                loading.setVisibility(View.GONE);
                videoHeight = iMediaPlayer.getVideoHeight();
                videoWidth = iMediaPlayer.getVideoWidth();
                showHideProgressInfo();
                if (!isLive) {
                    handler.removeCallbacks(runnable);
                    handler.post(runnable);
                }
                if (null != playListener) {
                    playListener.onPlay(null, 0, null, false);
                }
            }
        });
    }

    public IMediaPlayer.OnPreparedListener preparedListener;

    private void showHideProgressInfo() {
        handler.removeMessages(HIDE_PROGRESS);
        handler.sendEmptyMessageDelayed(HIDE_PROGRESS, DELAY_HIDE_TIME);
    }

    public void resetPlayer() {
        handler.removeCallbacks(runnable);
        position = -1;
        surface_view.stopPlayback();
        changePlayImage(true);
        currentItem = null;
        parentView.setVisibility(View.GONE);
        boolean isFullScreen = context.getResources().getConfiguration().orientation == Configuration
                .ORIENTATION_LANDSCAPE;
        if (isFullScreen) {
            changeScreenToPortrait();
        }
    }

    /**
     * 获取最大进度
     *
     * @return
     */
    public int getMaxTime() {
        return surface_view.getDuration();
    }

    /**
     * 获取当前播放进度
     *
     * @return
     */
    public int getCurrentTime() {
        return null == surface_view ? 0 : surface_view.getCurrentPosition();
    }

    public void setSeekTo() {
        if (null != surface_view) {
            surface_view.seekTo((int) seek_position);
        }
    }

    long seek_position = 0;

    private long setProgress() {
        if (surface_view == null || mDragging) return 0;

        long position = surface_view.getCurrentPosition();
        if (position < seekProgress) return seekProgress;
        seek_position = position;
        int duration = surface_view.getDuration();
        if (mediacontroller_seekbar != null) {
            if (duration > 0) {
                long pos = 1000L * position / duration;
                mediacontroller_seekbar.setProgress((int) pos);
            }
            int percent = surface_view.getBufferPercentage();
            mediacontroller_seekbar.setSecondaryProgress(percent * 10);
        }

        mDuration = duration;

        if (totaltime_tv != null) {
            totaltime_tv.setText(generateTime(mDuration));
        }
        if (nowtime_tv != null) {
            if (position > mDuration) {
                position = mDuration;
            }
            nowtime_tv.setText(generateTime(position));
        }
        if (null != progressListener) {
            progressListener.onPlayProgress(position);
        }
        return position;
    }

    public void play(View currentItem, int position, String playUrl, boolean isPlay) {
        this.currentItem = currentItem;
        this.position = position;
        play(playUrl);
    }

    /**
     * start ic_player_play
     *
     * @param playUrl
     */
    public void play(String playUrl) {
//        playUrl = "http://live-temp-litchi-hls-yf.jstv.com/live/ybs/online.m3u8";
        seekProgress = 0;
        this.playUrl = playUrl;
        setVisibility(View.VISIBLE);
        boolean isFullScreen = context.getResources().getConfiguration().orientation == Configuration
                .ORIENTATION_LANDSCAPE;
        if (context instanceof FullVideoActivity) {
            isFullScreen = true;
        }
        changeFullScreenViewImg(isFullScreen);
        changeSize(parentView, isFullScreen);
        changeSize(surface_view, isFullScreen);
        changePlayImage(false);
        parentView.setVisibility(View.VISIBLE);
        progressbar.setVisibility(View.VISIBLE);
        loading.setVisibility(View.VISIBLE);
//        surface_view.setVideoLayout(IjkVideoView.VIDEO_LAYOUT_SCALE);
        TableLayout tableLayout = new TableLayout(context);
        surface_view.setHudView(tableLayout);
        surface_view.setVideoPath(playUrl);
        surface_view.requestFocus();
        surface_view.start();
        isCompletion = false;
    }

    public void start() {
        changePlayImage(false);
        surface_view.start();
        isCompletion = false;
        if (!isLive) {
            handler.removeCallbacks(runnable);
            handler.post(runnable);
        }
    }

    public void pause() {
        //changePlayImage(true);
        surface_view.pause();
        handler.removeCallbacks(runnable);
    }

    public void restart(int position) {
        if (!surface_view.isPlaying()) {
            changePlayImage(false);
            surface_view.seekTo(position);
            surface_view.start();
            isCompletion = false;
            if (!isLive) {
                handler.removeCallbacks(runnable);
                handler.post(runnable);
            }
        }
    }

    /**
     * 是否正在播放
     *
     * @return
     */
    public boolean isPlaying() {
        if (null != surface_view && surface_view.isPlaying()) {
            return true;
        }
        return false;
    }

    public void pauseOrStart() {
        handler.removeCallbacks(runnable);
        if (surface_view.isPlaying()) {
            surface_view.pause();
            changePlayImage(true);
        } else {
            changePlayImage(false);
            surface_view.start();
            isCompletion = false;
            if (!isLive) {
                handler.post(runnable);
            }
        }
    }

    public void stop() {
        changePlayImage(true);
        handler.removeCallbacks(runnable);
        if (null != surface_view) {
            surface_view.stopPlayback();
        }
    }

    public interface OnCompleteListener {
        public void onCompletion();
    }

    public interface OnPlayListener {
        public void onPlay(View view, int position, String url, boolean isPlay);
    }

    public interface OnScreenChangeListener {
        public void onScreenChange(boolean isFullScreen);
    }

    public interface OnPlayProgressListener {
        public void onPlayProgress(long position);
    }

    public interface OnFullScreenReplyListener {
        public void onFullScreenReply(EditText editText);
    }

    public OnFullScreenReplyListener fullScreenReplyListener;

    public interface OnFullScreenPrisedListener {
        public void onFullScreenPrised();
    }

    public OnFullScreenPrisedListener fullScreenPrisedListener;

    public interface OnHeartListener {
        public void onHeart();
    }

    public OnHeartListener onHeartListener;
}

